package com.yihu.wlyy.web.patient.account;

import com.yihu.wlyy.entity.doctor.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.SignFamily;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.app.team.DrHealthTeamService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.EncodesUtil;
import com.yihu.wlyy.web.WeixinBaseController;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.utils.Encodes;

import java.util.List;

/**
 * 患者帳戶信息的Controller.
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/patient")
public class PatientController extends WeixinBaseController {

    @Autowired
    private PatientInfoService patientInfoService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private DrHealthTeamService doctorTeamService;
    @Autowired
    private DoctorService doctorService;

    /**
     * 患者基本信息查询接口
     *
     * @return
     */
    @RequestMapping(value = "baseinfo")
    @ResponseBody
    public String baseinfo() {
        try {
            Patient temp = patientInfoService.findByCode(getUID());
            SignFamily sanshi = familyContractService.findByPatientByType(getUID(), 1);
            SignFamily jiating = familyContractService.findByPatientByType(getUID(), 2);
            int sign = 0;
            if (sanshi != null && jiating != null) {
                sign = 3;
            } else if (jiating != null) {
                sign = 2;
            } else if (sanshi != null) {
                sign = 1;
            }
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置患者标识
                json.put("code", temp.getCode());
                // 设置患者姓名
                json.put("name", temp.getName());
                // 设置患者头像
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));
                // 设置患者年龄
                json.put("birthday", DateUtil.dateToStrShort(temp.getBirthday()));
                // 设置患者性别
                json.put("sex", temp.getSex());
                // 设置手机号码
                // json.put("mobile", CommonUtil.getMobileEncode(temp.getMobile()));
                json.put("mobile", temp.getMobile());
                // 设置身份证号
                json.put("idcard", CommonUtil.getIdcardEncode(temp.getIdcard()));//加密过的完整身份证
                // 设置社保卡号
                json.put("ssc", temp.getSsc());
                // 设置省
                json.put("province", temp.getProvince());
                // 设置市
                json.put("city", temp.getCity());
                // 设置区县
                json.put("area", temp.getTown());
                // 设置省名称
                json.put("provinceName", temp.getProvinceName());
                // 设置市名称
                json.put("cityName", temp.getCityName());
                // 设置区县名称
                json.put("areaName", temp.getTownName());
                // 设置街道
                json.put("street", temp.getStreet());
                // 设置街道名称
                json.put("streetName", temp.getStreetName());
                // 设置地址
                json.put("address", temp.getAddress());
                // 设置签约状态：0未签约，1三师，2家庭，3三师和家庭
                json.put("sign", sign);

                json.put("idcardAll", temp.getIdcard());//完整身份证
                return write(200, "患者信息查询成功！", "data", json);
            } else {
                return error(-1, "患者信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 患者基本信息保存
     *
     * @param photo    頭像
     * @param name     姓名
     * @param sex      性別
     * @param birthday 生日
     * @param ssc      社保卡號
     * @param province 省標識
     * @param city     市標識
     * @param town     區縣標識
     * @param address  詳細地址
     * @param street   街道
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(@RequestParam(required = false) String photo, @RequestParam(required = false) String name, @RequestParam(required = false) Integer sex, @RequestParam(required = false) String birthday, @RequestParam(required = false) String ssc, @RequestParam(required = false) String province, @RequestParam(required = false) String city, @RequestParam(required = false) String town, @RequestParam(required = false) String address, @RequestParam(required = false) String street) {
        try {
            Patient patient = patientInfoService.findByCode(getUID());
            if (StringUtils.isEmpty(photo)) {
                photo = fetchWxImages();
            }
            if (StringUtils.isNotEmpty(photo)) {
                photo = CommonUtil.copyTempImage(photo);
            }
            if (StringUtils.isNotEmpty(photo)) {
                patient.setPhoto(photo);
            }
            if (StringUtils.isNotEmpty(name))
                patient.setName(name);
            if (sex != null)
                patient.setSex(sex);
            if (StringUtils.isNotEmpty(birthday))
                patient.setBirthday(DateUtil.strToDate(birthday, DateUtil.YYYY_MM_DD));
//			if (StringUtils.isNotEmpty(ssc) && StringUtils.isEmpty(patient.getSsc()))
//				patient.setSsc(ssc);
           // if (StringUtils.isNotEmpty(province))
                patient.setProvince(province);
            //if (StringUtils.isNotEmpty(city))
                patient.setCity(city);
            //if (StringUtils.isNotEmpty(town))
                patient.setTown(town);
            //if (StringUtils.isNotEmpty(address))
                patient.setAddress(address);
            //if (StringUtils.isNotEmpty(street))
                patient.setStreet(street);
            if (patientInfoService.updatePatient(patient) != null) {
                // 修改成功
                return success("保存成功！");
            } else {
                // 注册失败
                return error(-1, "保存失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败！");
        }
    }

    /**
     * 患者信息查询接口
     *
     * @return
     */
    @RequestMapping(value = "info")
    @ResponseBody
    public String info() {
        try {
            Patient temp = patientInfoService.findByCode(getUID());
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置患者标识
                json.put("code", temp.getCode());
                // 设置患者姓名
                json.put("name", temp.getName());
                // 设置患者头像
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));
                // 设置患者出生年月
                json.put("birthday", DateUtil.dateToStr(temp.getBirthday(), DateUtil.YYYY_MM_DD));
                // 设置患者年龄
                json.put("age", DateUtil.getAgeByBirthday(temp.getBirthday()));
                // 设置患者性别
                json.put("sex", temp.getSex());
                // 设置患者病情：0绿标，1黄标，2红标
                json.put("diseaseLevel", temp.getDiseaseCondition());
                // 查询签约信息
                SignFamily signContract = familyContractService.findByPatient(getUID());
                if (signContract == null) {
                    // 设置签约日期
                    json.put("qyrq", "");
                    // 设置健康管理师
                    json.put("health", "");
                    // 设置专科医生
                    json.put("specialist", "");
                    // 设置全科医生
                    json.put("gp", "");
                } else {
                    // 设置签约日期
                    json.put("qyrq", DateUtil.dateToStr(signContract.getBegin(), DateUtil.YYYY_MM_DD));
                    // // 查询三师医生信息
                    // List<DoctorTeamInfo> doctorTeamInfos = doctorTeamService.findDoctorByTeam(signContract.getTeam());
                    // if (doctorTeamInfos != null) {
                    // for (DoctorTeamInfo doctorTeamInfo : doctorTeamInfos) {
                    // if (doctorTeamInfo.getType() == 1) {
                    // json.put("specialist", doctorTeamInfo.getName());
                    // } else if (doctorTeamInfo.getType() == 2) {
                    // json.put("gp", doctorTeamInfo.getName());
                    // } else
                    // json.put("health", doctorTeamInfo.getName());
                    // }
                    // } else {
                    json.put("health", "");
                    json.put("specialist", "");
                    json.put("gp", "");
                    // }
                }
                return write(200, "患者信息查询成功！", "data", json);
            } else {
                return error(-1, "患者信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 修改密码
     *
     * @param oldpwd 旧密码
     * @param newpwd 新密码
     * @return
     */
    @RequestMapping(value = "updatepwd")
    @ResponseBody
    public String updatepwd(String oldpwd, String newpwd) {
        try {
            Patient patient = patientInfoService.findByCode(getUID());
            if (patient == null) {
                return error(-1, "修改失败！");
            } else {
                String encodePWD = EncodesUtil.entryptPassword(Encodes.decodeHex(patient.getSalt()), oldpwd);
                if (StringUtils.equals(patient.getPassword(), encodePWD)) {
                    patient.setPassword(newpwd);
                    patientInfoService.updatePatientPwd(patient);
                    return success("修改成功！");
                } else {
                    return error(-1, "修改失败：旧密码错误！");
                }
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "修改失败！");
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping(value = "loginout")
    @ResponseBody
    public String loginout() {
        try {
            tokenService.delToken(1, getUID());
            return success("已成功退出！");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败！");
        }
    }

    /**
     * 微信用户退出登录
     *
     * @return
     */
    @RequestMapping(value = "wxloginout")
    @ResponseBody
    public String wxloginout() {
        try {
            Patient patient = patientInfoService.findByCode(getUID());
            if (patient == null) {
                return error(-1, "退出失败，用户不存在");
            } else {
                patient.setOpenid("");
                patientInfoService.updateUser(patient);
            }
            return success("已成功退出！");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败！");
        }
    }

    /**
     * 登录患者获取三师信息
     *
     * @return
     */
    @RequestMapping(value = "teachers")
    @ResponseBody
    public String teachers() {
        try {
            String code = getUID();//getUID();
            // 查询签约信息
            SignFamily signContract = familyContractService.findBySanshiPatient(code);
            if (signContract == null) {
                return error(1, "无三师签约信息");
            }
            JSONObject doctorJson = new JSONObject();
            // 设置签约日期
            doctorJson.put("qyrq", DateUtil.dateToStr(signContract.getBegin(), DateUtil.YYYY_MM_DD));
            // 查询三师医生信息
            List<Doctor> doctors = doctorTeamService.findSanshiTeamDoctors(code);
            JSONArray jsonArray = new JSONArray();
            if (doctors != null) {
                for (Doctor doctor : doctors) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", CommonUtil.getPhoneUrl(doctor.getPhoto()));
                    json.put("hospitalName", doctor.getHosptialName());
                    json.put("deptName", doctor.getDeptName());
                    json.put("jobName", doctor.getJobName());
                    json.put("expertise", doctor.getExpertise());
                    int type = doctor.getLevel();
                    if (type == 1) {
                        json.put("typename", "专科医生");
                    } else if (type == 2) {
                        json.put("typename", "全科医生");
                    } else if (type == 3) {
                        json.put("typename", "健康管理师");
                    } else {
                        json.put("typename", "");
                    }
                    json.put("type", type);
                    jsonArray.put(json);
                }
            }
            doctorJson.put("list", jsonArray);
            return write(200, "查询成功！", "data", doctorJson);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 医生基本信息查询接口
     *
     * @param doctor 医生标识
     * @return
     */
    @RequestMapping(value = "docInfo")
    @ResponseBody
    public String doctorInfo(String doctor) {
        try {
            Doctor temp = doctorService.findDoctorByCode(doctor);
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置医生标识
                json.put("code", temp.getCode());
                // 设置医生姓名
                json.put("name", temp.getName());
                // 设置医生头像
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));
                // 设置医生性别
                json.put("sex", temp.getSex());
                // 设置省名称
                json.put("provinceName", temp.getProvinceName());
                // 设置城市名称
                json.put("cityName", temp.getCityName());
                // 设置医院名称
                json.put("hospitalName", temp.getHosptialName());
                // 设置部门名称
                json.put("deptName", temp.getDeptName());
                // 设置职称
                json.put("jobName", temp.getJobName());
                // 设置医生专长
                json.put("expertise", temp.getExpertise());
                // 设置医生简介
                json.put("introduce", temp.getIntroduce());
                // 二维码地址
                json.put("qrcode", temp.getQrcode());
                return write(200, "医生信息查询成功！", "data", json);
            } else {
                return error(-1, "医生信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败！");
        }
    }

    /**
     * 查询患者签约状态
     *
     * @return
     */
    @RequestMapping(value = "sign_status")
    @ResponseBody
    public String signStaus() {
        try {
            JSONArray teamDoctors = new JSONArray();
            JSONArray familyDoctors = new JSONArray();
            String id = getUID();
            //查询家庭签约
            SignFamily jt = familyContractService.findByPatientYes(id);
            if (jt != null) {
                List<Doctor> doctors = doctorTeamService.findJiatingTeamDoctors(id);
                if (doctors != null) {
                    for (Doctor doctor : doctors) {
                        if (doctor == null) {
                            continue;
                        }
                        familyDoctors.put(doctor.getName());
                    }
                }
            }
            // 查询三师医生
            SignFamily ss = familyContractService.findBySanshiPatientYes(id);
            if (ss != null) {
                List<Doctor> doctors = doctorTeamService.findSanshiTeamDoctors(id);
                if (doctors != null) {
                    for (Doctor doctor : doctors) {
                        if (doctor == null) {
                            continue;
                        }
                        teamDoctors.put(doctor.getName());
                    }
                }
            }
            // 未签约
            int sign = 0;
            if (ss != null && jt != null) {
                // 三师+家庭
                sign = 3;
            } else if (jt != null) {
                // 家庭签约
                sign = 2;
            } else if (ss != null) {
                // 三师签约
                sign = 1;
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "获取签约状态成功！");
            json.put("data", sign);
            json.put("teamDoctors", teamDoctors);
            json.put("familyDoctors", familyDoctors);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "签约状态查询失败！");
        }
    }

    /**
     * 查询患者签约状态
     *
     * @return
     */
    @RequestMapping(value = "sign_doctors")
    @ResponseBody
    public String signDoctors() {
        try {
            JSONArray teamDoctors = new JSONArray();
            JSONArray familyDoctors = new JSONArray();
            String id = getUID();
            //查询家庭签约
            SignFamily jt = familyContractService.findByPatientYes(id);
            if (jt != null) {
                List<Doctor> doctors = doctorTeamService.findJiatingTeamDoctors(id);
                if (doctors != null) {
                    for (Doctor doctor : doctors) {
                        if (doctor == null) {
                            continue;
                        }
                        JSONObject doctorJson = new JSONObject();
                        doctorJson.put("code", doctor.getCode());
                        doctorJson.put("name", doctor.getName());
                        doctorJson.put("level", doctor.getLevel());
                        familyDoctors.put(doctorJson);
                    }
                }
            }
            // 查询三师医生
            SignFamily ss = familyContractService.findBySanshiPatientYes(id);
            if (ss != null) {
                List<Doctor> doctors = doctorTeamService.findSanshiTeamDoctors(id);
                if (doctors != null) {
                    for (Doctor doctor : doctors) {
                        if (doctor == null) {
                            continue;
                        }
                        JSONObject doctorJson = new JSONObject();
                        doctorJson.put("code", doctor.getCode());
                        doctorJson.put("name", doctor.getName());
                        doctorJson.put("level", doctor.getLevel());
                        teamDoctors.put(doctorJson);
                    }
                }
            }
            // 未签约
            int sign = 0;
            if (ss != null && jt != null) {
                // 三师+家庭
                sign = 3;
            } else if (jt != null) {
                // 家庭签约
                sign = 2;
            } else if (ss != null) {
                // 三师签约
                sign = 1;
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "获取签约状态成功！");
            json.put("data", sign);
            json.put("teamDoctors", teamDoctors);
            json.put("familyDoctors", familyDoctors);
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "签约状态查询失败！");
        }
    }

    /**
     * 查询患者是否有签约信息
     *
     * @return
     */
    @RequestMapping(value = "is_sign")
    @ResponseBody
    public String isSign() {
        try {
            JSONObject jsonObject = new JSONObject();
            //判断是否有三师签约
            SignFamily ss = familyContractService.findBySanshiPatient(getUID());  // -1 未签约  0 待签约 1 已签约 2待解约
            if (ss != null) {
                return write(200, "获取签约状态成功！", "data", ss.getStatus());
            }
            //判断是否有家庭签约
            SignFamily sf = familyContractService.findByJiatingPatient(getUID());
            if (sf != null) {
                return write(200, "获取签约状态成功！", "data", sf.getStatus());
            }
            return write(200, "获取签约状态成功！", "data", -1);
        } catch (Exception e) {
            error(e);
            return error(-1, "签约状态查询失败！");
        }
    }

    /**
     * 查询患者身份证号
     *
     * @return
     */
    @RequestMapping(value = "idc")
    @ResponseBody
    public String idcard() {
        try {
            Patient temp = patientInfoService.findByCode(getUID());
            return write(200, "患者信息查询成功！", "data", temp.getIdcard());
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 根據邀請紀錄查詢邀請人信息
     *
     * @return
     */
    @RequestMapping(value = "getPatientByInviLogCode")
    @ResponseBody
    public String getPatientByInviLogCode(String invilogCode) {
        try {
            Patient temp = patientInfoService.invilogCode(invilogCode);
            if (temp != null) {
                JSONObject json = new JSONObject();
                json.put("code", temp.getCode());    // 设置患者标识
                json.put("name", temp.getName());// 设置患者姓名
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));// 设置患者头像
                json.put("birthday", DateUtil.dateToStrShort(temp.getBirthday()));// 设置患者年龄
                json.put("sex", temp.getSex());// 设置患者性别
                // json.put("mobile", CommonUtil.getMobileEncode(temp.getMobile()));
                json.put("mobile", temp.getMobile());// 设置手机号码
                json.put("idcard", CommonUtil.getIdcardEncode(temp.getIdcard()));// 设置身份证号
                json.put("ssc", temp.getSsc());// 设置社保卡号
                json.put("province", temp.getProvince());// 设置省
                json.put("city", temp.getCity());// 设置市
                json.put("area", temp.getTown());    // 设置区县
                json.put("provinceName", temp.getProvinceName());// 设置省名称
                json.put("cityName", temp.getCityName());// 设置市名称
                json.put("areaName", temp.getTownName());// 设置区县名称
                json.put("street", temp.getStreet());        // 设置街道
                json.put("streetName", temp.getStreetName());// 设置街道名称
                json.put("address", temp.getAddress());// 设置地址
                return write(200, "患者信息查询成功！", "data", json);
            } else {
                return error(-1, "患者信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }
}
